<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="divport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="renderer" content="webkit">
    <title></title>
    <link href="css/mui.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="css/public.css" />
    <link rel="stylesheet" href="css/common.css" />
    <link rel="stylesheet" href="css/chat.css" />
    <script type="text/javascript" src="js/common.js" ></script>
</head>
<body>
	<div id="hearder">
		<img src="img/goBack.png">
		<h3>客服</h3>
		<span>客服</span>
	</div>
	<div id="main">
		<div id="downPull"><span>下拉加载</span><br/><img src="img/5-121204194026.gif"/></div>
		<ul class="chatList">
			
		</ul>
	</div>
	<div id="footer_chat">
		<div class="issueIpt">
			<input class="inputBox" id="inputBox" type="text" placeholder="请输入您的消息"/>
			<img class="expression" src="img/issueExpressions.png" /> 
			<img class="more" src="img/issuePictures.png" /> 
			<span class="send">发送</span>
		</div>
		<div class="issuePictures clear">
			<div class="photograph">
				<img src="img/photograph.png" />
                    <!--<input type="file" id="uploadphoto" name="images" value=""  capture="camera" accept="image/*"  style="opacity: 0" />-->
                    <input type="hidden" id="picIndex" value="0"/>
                    <input type="hidden" id="uploadphoto" style="opacity: 0"/>
			</div>
			<!--<div class="addimg">
				<img src="img/addimg.png" /> 
				<input class="uploadImg" type="file"/>
			</div>-->
		</div>	
		<div class="issueExpressions">
			
		</div>	
	</div>
</body>
<script src="js/jquery-1.8.3.min.js"></script>
<script src='js/jquery.form.js'></script>
<script src="js/jquery.qqFace.js"></script>
<script src="js/mui.min.js"></script>
<script src="js/mui.previewimage.js"></script>
<script src="js/mui.zoom.js"></script>
<script src="layui/layui.js"></script>
<script src="js/commonNew.js"></script>
<script src="js/chat.js"></script>
<script type="text/javascript">
	
	var kefu=JSON.parse(storage.getItem("userinfo"));
	if(kefu.user_id==null){
		taostr("此账号暂未开通客服功能！",1000);
		location.href="index.html"
	}
	console.log(JSON.parse(storage.getItem("userinfo")))
	var toid=getUrlParam("id")
	var historyData=JSON.parse(storage.getItem("historyData"));
	console.log(historyData)
    if (historyData == null) {
        historyData = {
            'data': []    
        }
    }
    
    layui.use('layim', function(layim){
        //基础配置
        layim.config({

            //获取主面板列表信息
            init: {
                url: "{:url('index/getList')}" //接口地址（返回的数据格式见下文）
                ,type: 'get' //默认get，一般可不填
                ,data: {} //额外参数
            }
            //获取群员接口
            ,members: {
                url: "{:url('index/getMembers')}" //接口地址（返回的数据格式见下文）
                ,type: 'get' //默认get，一般可不填
                ,data: {} //额外参数
            }
            ,brief: true //是否简约模式（默认false，如果只用到在线客服，且不想显示主面板，可以设置 true）
            ,title: '我的LayIM' //主面板最小化后显示的名称
            ,maxLength: 3000 //最长发送的字符长度，默认3000
            ,isfriend: true //是否开启好友（默认true，即开启）
            ,isgroup: true //是否开启群组（默认true，即开启）
            ,right: '0px' //默认0px，用于设定主面板右偏移量。该参数可避免遮盖你页面右下角已经的bar。
            ,chatLog: "{:url('Chatlog/index')}" //聊天记录地址（如果未填则不显示）
            ,find: "{:url('findgroup/index')}" //查找好友/群的地址（如果未填则不显示）
            ,copyright: false //是否授权，如果通过官网捐赠获得LayIM，此处可填true
        });
        //建立WebSocket通讯
        //var local='192.168.1.109';
        var local='47.94.17.241';
        var socket = new WebSocket('ws://'+local+':7272');
        //连接成功时触发
        socket.onopen = function(){
            // 登录
            var login_data = '{"type":"init","id":"'+kefu.user_id+'","username":"'+kefu.nickname+'","avatar":"'+kefu.pimg_url+'","sign":""}';
            socket.send( login_data );
            console.log( login_data );
            console.log("websocket握手成功!");
        };       
        for(var i=0;i<historyData.data.length;i++){
        	if(historyData.data[i].id==toid){
        		historyData.data[i].prompt=0;
        		storage.setItem("historyData",JSON.stringify(historyData));	 
        		for(var j=0;j<historyData.data[i].arrData.length;j++){
        			if(historyData.data[i].arrData[j].mine){
		                var img= historyData.data[i].arrData[j].content.substring(0,4);
		                var img1= historyData.data[i].arrData[j].content.substring(historyData.data[i].arrData[j].content.length-1);
		                var content;
		                if(img=="img[" && img1=="]" ){
		                    content=' <img class="chat_img" src="'+historyData.data[i].arrData[j].content.substring(4,historyData.data[i].arrData[j].content.length-1)+'" data-preview-src="" data-preview-group="1">'
		                }else {
		                    content='<p>'+replace_em(historyData.data[i].arrData[j].content)+'</p>'
		                }
		                var str='<li class="issue clear">'
		                    +'<div class="issueChatImg"></div>'
		                    +'<div class="newTimer">'+timer+'         <!-- <span>{$uinfo.username}</span> --></div>'
		                    +'<img  class="figureImg figureImg_r" src="img/product.png">'
		                    +content
		                    +'</li>';
		                $(".chatList").append(str)
		                $(".inputBox").val("");
		                $(".send").hide();
		                $(".more").css("display","inline-block");
		            }else{
		                var img= historyData.data[i].arrData[j].content.substring(0,4);
		                var img1= historyData.data[i].arrData[j].content.substring(historyData.data[i].arrData[j].content.length-1);
		                var timer=timestampToTime(historyData.data[i].arrData[j].timestamp)
		                var content;
		                if(img=="img[" && img1=="]" ){
		                    content=' <img class="chat_img" src="'+historyData.data[i].arrData[j].content.substring(4,historyData.data[i].arrData[j].content.length-1)+'" data-preview-src="" data-preview-group="1">'
		                }else {
		                    content='<p>'+replace_em(historyData.data[i].arrData[j].content)+'</p>'
		                }
		                var str='<li class="received clear">'
		                    +'<div class="receivedChatImg"></div>'
		                    +'<div class="newTimer"><!--'+historyData.data[i].arrData[j].username+' -->    '+timer+'</div>'
		                    +'<img  class="figureImg figureImg_l" src="'+historyData.data[i].arrData[j].avatar+'">'
		                    +content
		                    +'</li>';
		                $(".chatList").append(str);
		            }
        		}
        	}
        }
        $('html, body').animate({scrollTop: $(document).height()}, 50)
        //监听收到的消息
        socket.onmessage = function(res){
            //console.log(res.data);
            var data = eval("("+res.data+")");
            switch(data['message_type']){
                // 服务端ping客户端
                case 'ping':
                    socket.send('{"type":"ping"}');
                    break;
                // 登录 更新用户列表
                case 'init':
                    console.log(res.data);
                    //console.log(data['id']+"登录成功");
                    //layim.getMessage(res.data); //res.data即你发送消息传递的数据（阅读：监听发送的消息）
                    break;
                // 检测聊天数据
                case 'chatMessage':                
                    console.log(data.data);
                    var img= data.data.content.substring(0,4);
                    var img1= data.data.content.substring(data.data.content.length-1);
                    var timer=timestampToTime(data.data.timestamp)
                    var content;
                    if(img=="img[" && img1=="]" ){
                        content=' <img class="chat_img" src="'+data.data.content.substring(4,data.data.content.length-1)+'" data-preview-src="" data-preview-group="1">'
                    }else {
                        content='<p>'+replace_em(data.data.content)+'</p>'
                    }
                    var str='<li class="received clear">'
                        +'<div class="receivedChatImg"></div>'
                        +'<div class="newTimer"><!--'+data.data.username+' -->    '+timer+'</div>'
                        +'<img  class="figureImg figureImg_l" src="'+data.data.avatar+'">'
                        +content
                        +'</li>';
                    $(".chatList").append(str);
                    $('html, body').animate({scrollTop: $(document).height()}, 50);
                    for(var i=0;i<historyData.data.length;i++){
		                if(historyData.data[i].id==data.data.id){
		                	historyData.data[i].arrData.push(data.data);
		                	historyData.data[i].prompt=parseInt(historyData.data[i].prompt)+1
		                	console.log(historyData)
		                	storage.setItem("historyData",JSON.stringify(historyData));	  
		                	return;
		                }
	                }
                    //layim.getMessage(data.data);
                    break;
                // 离线消息推送
                case 'logMessage':
				for(var i=0;i<historyData.data.length;i++){
				        	if(historyData.data[i].id==toid){
				        		historyData.data[i].prompt=0;
				        		storage.setItem("historyData",JSON.stringify(historyData));	 
				        		for(var j=0;j<historyData.data[i].arrData.length;j++){
				        			if(historyData.data[i].arrData[j].mine){
						                var img= historyData.data[i].arrData[j].content.substring(0,4);
						                var img1= historyData.data[i].arrData[j].content.substring(historyData.data[i].arrData[j].content.length-1);
						                var content;
						                if(img=="img[" && img1=="]" ){
						                    content=' <img class="chat_img" src="'+historyData.data[i].arrData[j].content.substring(4,historyData.data[i].arrData[j].content.length-1)+'" data-preview-src="" data-preview-group="1">'
						                }else {
						                    content='<p>'+replace_em(historyData.data[i].arrData[j].content)+'</p>'
						                }
						                var str='<li class="issue clear">'
						                    +'<div class="issueChatImg"></div>'
						                    +'<div class="newTimer">'+timer+'         <!-- <span>{$uinfo.username}</span> --></div>'
						                    +'<img  class="figureImg figureImg_r" src="img/product.png">'
						                    +content
						                    +'</li>';
						                $(".chatList").append(str)
						                $(".inputBox").val("");
						                $(".send").hide();
						                $(".more").css("display","inline-block");
						            }else{
						                var img= historyData.data[i].arrData[j].content.substring(0,4);
						                var img1= historyData.data[i].arrData[j].content.substring(historyData.data[i].arrData[j].content.length-1);
						                var timer=timestampToTime(historyData.data[i].arrData[j].timestamp)
						                var content;
						                if(img=="img[" && img1=="]" ){
						                    content=' <img class="chat_img" src="'+historyData.data[i].arrData[j].content.substring(4,historyData.data[i].arrData[j].content.length-1)+'" data-preview-src="" data-preview-group="1">'
						                }else {
						                    content='<p>'+replace_em(historyData.data[i].arrData[j].content)+'</p>'
						                }
						                var str='<li class="received clear">'
						                    +'<div class="receivedChatImg"></div>'
						                    +'<div class="newTimer"><!--'+historyData.data[i].arrData[j].username+' -->    '+timer+'</div>'
						                    +'<img  class="figureImg figureImg_l" src="'+historyData.data[i].arrData[j].avatar+'">'
						                    +content
						                    +'</li>';
						                $(".chatList").append(str);
						            }
				        		}
				        	}
				        }
                    //setTimeout(function(){layim.getMessage(data.data)}, 1000);
                    break;
                // 用户退出 更新用户列表
                case 'logout':
                    break;
                //聊天还有不在线
                case 'ctUserOutline':
                    //console.log('11111');
                    //layer.msg('好友不在线', {'time' : 1000});
                    break;

            }
        };       

        $(".send").on("click",function () {
           var content= $("#inputBox").val()
            console.log(content)
            var mine = '{"username":"'+kefu.nickname+'","avatar":"'+kefu.pimg_url+'","id":"'+kefu.user_id+'","mine":true,"content":"'+content+'"}';
            var to = '{"username":"buhaoxiao","id":'+toid+',"avatar":"/uploads/20180416/23bc86fe78be6fe32e56f14263383c79.jpg","sign":"前端就是这么牛","name":"buhaoxiao","type":"friend"}';
            var login_data = '{"type":"chatMessage","data":{"mine":'+mine+', "to":'+to+'}}';
            socket.send( login_data );
            var timer=Date.parse(new Date())
            var newMine = '{"username":"{$uinfo.username}","avatar":"{$uinfo.avatar}","id":"{$uinfo.id}","timestamp":'+timer+',"mine":true,"content":"'+content+'"}';
            for(var i=0;i<historyData.data.length;i++){
                if(historyData.data[i].id==toid){
                	historyData.data[i].arrData.push(JSON.parse(newMine));
                }
            }
            storage.setItem("historyData",JSON.stringify(historyData));
            var replace=replace_em(content);          
            var str='<li class="issue clear">'
                +'<div class="issueChatImg"></div>'
                +'<div class="newTimer">'+timestampToTime(new Date())+'         <!-- <span>'+kefu.nickname+'</span> --></div>'
                +'<img  class="figureImg figureImg_r" src="'+kefu.pimg_url+'">'
                +'<p>'+replace+'</p>'
                +'</li>';
            $(".chatList").append(str)
            $(".inputBox").val("");
            $(".send").hide();
            $(".more").css("display","inline-block");
            $('html, body').animate({scrollTop: $(document).height()}, 50)
        })
        
        
        
        $(".photograph").on("click",function() {
        	var bts = [{    
                title: "拍照"    
            }, {    
                title: "从相册选择"    
            }];    
            plus.nativeUI.actionSheet({    
                    cancel: "取消",    
                    buttons: bts    
                },    
                function(e) {    
                    if (e.index == 1) {    
                                   var cmr = plus.camera.getCamera();    
						           cmr.captureImage(function(p) {    
						               plus.io.resolveLocalFileSystemURL(p, function(entry) {    
						               			           var name="_doc/upload/"+entry.name;  
						           plus.zip.compressImage({    
						                   src:entry.toLocalURL(),//src: (String 类型 )压缩转换原始图片的路径    
						                   dst:name,//压缩转换目标图片的路径    
						                   quality:40,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100    
						                   overwrite:true//overwrite: (Boolean 类型 )覆盖生成新文件    
						               },    
						               function(zip) {  
						                   //页面显示图片  
						                     
								            	plus.io.resolveLocalFileSystemURL(zip.target,function(entry){  
								                entry.file( function(file){  
								                    var fileReader = new plus.io.FileReader();  
								                    fileReader.readAsDataURL(file);  
								                    fileReader.onloadend = function(e) {  
								                       var picUrl = e.target.result.toString(); 
								                        console.log(picUrl)       
								                        
								                 
								                
								                  		var mine = '{"username":"'+kefu.nickname+'","avatar":"'+kefu.pimg_url+'","id":"'+kefu.user_id+'","mine":true,"content":"img['+picUrl+']"}';
										                  var to = '{"username":"buhaoxiao","id":'+toid+',"avatar":"/uploads/20180416/23bc86fe78be6fe32e56f14263383c79.jpg","sign":"前端就是这么牛","name":"buhaoxiao","type":"friend"}';
										                  var login_data = '{"type":"chatMessage","data":{"mine":'+mine+', "to":'+to+'}}';
										                  socket.send( login_data );
										                  var timer=Date.parse(new Date())
										                  var newMine = '{"username":"{$uinfo.username}","avatar":"{$uinfo.avatar}","id":"{$uinfo.id}","timestamp":"'+timer+'","mine":true,"content":"img['+picUrl+']"}';
										                  for(var i=0;i<historyData.data.length;i++){
												                if(historyData.data[i].id==toid){
												                	historyData.data[i].arrData.push(JSON.parse(newMine));
												                }
											                }
										                  storage.setItem("historyData",JSON.stringify(historyData));
								                        var nowIndex = parseInt(picIndex)+1;  
								                        $("#picIndex").val(nowIndex);  
								                        $("#uploadphoto").val(picUrl);                        
								                        var html = '';  
								                        var html='<li class="issue clear">'
											                      +'<div class="issueChatImg"></div>'
											                      +'<div class="newTimer">'+timestampToTime(new Date())+'         <!-- <span>'+kefu.nickname+'</span> --></div>'
											                      +'<img  class="figureImg figureImg_r" src="'+kefu.pimg_url+'">'
											                      +'<img class="chat_img" src="'+picUrl+'" data-preview-src="" data-preview-group="1">'
											                      +'</li>';                      
								                        $(".chatList").append(html);   
								                        $('html, body').animate({scrollTop: $(document).height()}, 50)
								                  }  
								               });  
								          }); 
						               },function(error) {    
						                   plus.nativeUI.toast("压缩图片失败，请稍候再试");    
						           }); 
						                     
						               }, function(e) {    
						                   plus.nativeUI.toast("读取拍照文件错误：" + e.message);    
						               });    
						           }, function(e) {    
						           }, {    
						               filter: 'image'   
						           });     
                    } else if (e.index == 2) {    
                                    plus.gallery.pick(function(e) {    
				                var name = e.substr(e.lastIndexOf('/') + 1);  
				               compressImage(e,name);  
				            }, function(e) {    
				            }, {    
				                filter: "image"    
				            });   
                    }    
                }    
            );    
        	
        })     
        
        
        
//      $("#uploadphoto").change(function() {
//          $("#myupload").ajaxSubmit({
//              dataType: 'json', //数据格式为json
//              beforeSend: function () { //开始上传
//              },
//              uploadProgress: function (event, position, total, percentComplete) {
//              },
//              success: function (data) {
//                  console.log(data);
//                  var mine = '{"username":"{$uinfo.username}","avatar":"{$uinfo.avatar}","id":"{$uinfo.id}","mine":true,"content":"img['+data.path+']"}';
//                  var to = '{"username":"buhaoxiao","id":'+toid+',"avatar":"/uploads/20180416/23bc86fe78be6fe32e56f14263383c79.jpg","sign":"前端就是这么牛","name":"buhaoxiao","type":"friend"}';
//                  var login_data = '{"type":"chatMessage","data":{"mine":'+mine+', "to":'+to+'}}';
//                  socket.send( login_data );
//                  var timer=Date.parse(new Date())
//                  var newMine = '{"username":"{$uinfo.username}","avatar":"{$uinfo.avatar}","id":"{$uinfo.id}","timestamp":"'+timer+'","mine":true,"content":"img['+data.path+']"}';
//                  for(var i=0;i<historyData.data.length;i++){
//		                if(historyData.data[i].id==toid){
//		                	historyData.data[i].arrData.push(JSON.parse(newMine));
//		                }
//	                }
//                  storage.setItem("historyData",JSON.stringify(historyData));
//                  var str='<li class="issue clear">'
//                      +'<div class="issueChatImg"></div>'
//                      +'<div class="newTimer">'+timestampToTime(new Date())+'         <!-- <span>{$uinfo.username}</span> --></div>'
//                      +'<img  class="figureImg figureImg_r" src="img/product.png">'
//                      +'<img class="chat_img" src="'+data.path+'" data-preview-src="" data-preview-group="1">'
//                      +'</li>';
//                  $(".chatList").append(str);
//                  $(".issuePictures").css("display","none");
//                  $('html, body').animate({scrollTop: $(document).height()}, 50)
//              },
//              error: function (xhr) { //上传失败
//                  alert("发送失败");
//              }
//          });
//      });
  });    
 
   
   
   
   
   
</script>
</html>
